package remoting

import (
	"bbq/common/logger"
	"encoding/binary"
	"github.com/panjf2000/gnet"
	"github.com/panjf2000/gnet/pkg/pool/goroutine"
	"log"
)

/*
  远程通信服务端
*/

type GnetRemoteServer struct {
	base *GnetRemoteBase

	Config *RemoteServerConfig

	logger logger.Logger
}

//服务配置
type RemoteServerConfig struct {
	Port string //端口号
}

func NewGnetRemoteServer(logger logger.Logger) *GnetRemoteServer {
	return &GnetRemoteServer{
		base:   newGnetRemoteBase(),
		logger: logger,
	}
}

/*
 * 注册处理器
 */
func (ts *GnetRemoteServer) RegisterProcessor(code int16, processor GnetRequestProcessor, executor *goroutine.Pool) {
	ts.base.RegisterProcessor(code, processor, executor)
}

//启动
func (s *GnetRemoteServer) Start() {
	//编解码器
	encoderConfig := gnet.EncoderConfig{
		ByteOrder:                       binary.LittleEndian,
		LengthFieldLength:               4,
		LengthAdjustment:                0,
		LengthIncludesLengthFieldLength: false,
	}
	decoderConfig := gnet.DecoderConfig{
		ByteOrder:           binary.LittleEndian,
		LengthFieldOffset:   0,
		LengthFieldLength:   4,
		LengthAdjustment:    0,
		InitialBytesToStrip: 4,
	}
	codec := gnet.NewLengthFieldBasedFrameCodec(encoderConfig, decoderConfig)

	log.Fatal(gnet.Serve(s.base, "tcp://:"+s.Config.Port, gnet.WithMulticore(true),
		gnet.WithCodec(codec)))
}
